﻿using System;
using System.DirectoryServices;
using System.Collections.Generic;
using System.Linq;

using LDAP.Entity;
using System.Collections;

namespace LDAP.BLL
{
    /// <summary>
    /// BizUser 的摘要说明
    /// </summary>
    public class BizUser
    {
        public BizUser()
        {
            
        }

        public static string GetUserName(string id){
            string msg = String.Empty;
            return AllUser(ref msg).FirstOrDefault(l => l.Id == id).UserName;
        }

        public static User Login(string username, string password, ref string message)
        {
            string ldapPath = "LDAP://10.5.17.25/OU=17173_users,DC=17173-family,DC=com";

            string ldapUser = "CN=" + username + ",OU=17173_users,DC=17173-family,DC=com";
            DirectoryEntry entry = new DirectoryEntry(ldapPath, ldapUser, password, AuthenticationTypes.None);
            try
            {
                Object obj = entry.NativeObject;
                DirectorySearcher search = new DirectorySearcher(entry);
                search.Filter = "(&(objectClass=user)(sAMAccountName=" + username + "))";

                SearchResult result = search.FindOne();

                User user = new User
                {
                    Id = result.Properties["cn"].Count > 0 ? (String)result.Properties["cn"][0] : "",
                    UserName = result.Properties["displayname"].Count > 0 ? (String)result.Properties["displayname"][0] : "",
                    Email = result.Properties["mail"].Count > 0 ? (String)result.Properties["mail"][0] : "",
                    DeptName = result.Properties["description"].Count > 0 ? (String)result.Properties["description"][0] : "",
                    Status = (DateTime.Now - (new DateTime(1601, 1, 1, 0, 0, 0, DateTimeKind.Utc))).Seconds > ((result.Properties["accountexpires"].Count > 0 ? (Int64)(result.Properties["accountexpires"][0]) : 0) / 10000)
                            ? UserStatus.Work : UserStatus.Leave
                };
                user.DeptName = user.DeptName.Replace("17173-", "");
                return user;
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return null;
            }
        }

        public static List<User> AllUser(ref string message)
        {
            if (Tools.CacheUtil.Exists("alluser_17173ldap"))
                return Tools.CacheUtil.Get("alluser_17173ldap") as List<User>;

            string ldapPath = "LDAP://10.5.17.25/OU=17173_users,DC=17173-family,DC=com";

            DirectoryEntry entry = new DirectoryEntry(ldapPath, "CN=enterprise,OU=project,OU=17173_temp,DC=17173-family,DC=com", "17173ep!@#", AuthenticationTypes.None);
            try
            {
                Object obj = entry.NativeObject;
                DirectorySearcher searcher = new DirectorySearcher(entry);

                searcher.Filter = "(objectClass=user)";

                List<User> all = new List<User>();
                foreach (SearchResult result in searcher.FindAll())
                {
                    User user = new User
                    {
                        Id = result.Properties["cn"].Count > 0 ? (String)result.Properties["cn"][0] : "",
                        UserName = result.Properties["displayname"].Count > 0 ? (String)result.Properties["displayname"][0] : "",
                        Email = result.Properties["mail"].Count > 0 ? (String)result.Properties["mail"][0] : "",
                        DeptName = result.Properties["description"].Count > 0 ? (String)result.Properties["description"][0] : "",
                        Status = (DateTime.Now - (new DateTime(1601, 1, 1, 0, 0, 0, DateTimeKind.Utc))).Seconds > ((result.Properties["accountexpires"].Count > 0 ? (Int64)(result.Properties["accountexpires"][0]) : 0) / 10000)
                            ? UserStatus.Work : UserStatus.Leave
                    };
                    user.DeptName = user.DeptName.Replace("17173-", "");
                    all.Add(user);
                }

                Tools.CacheUtil.Insert("alluser_17173ldap", all, 3600);

                return all;
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return null;
            }
        }

        public static List<Hashtable> AllDept() {
            if (Tools.CacheUtil.Exists("alldept_17173ldap"))
                return Tools.CacheUtil.Get("alldept_17173ldap") as List<Hashtable>;

            string message = "";
            List<Hashtable> list = new List<Hashtable>();

            foreach (string dept in string.Join(";", AllUser(ref message).Select(l => l.DeptName).ToArray()).Split(';').Distinct().OrderBy(l => l)) {
                Hashtable ht = new Hashtable();
                ht.Add("name", dept);
                ht.Add("py", Tools.StringUtil.GetChineseSpell(dept));
                ht.Add("id", dept);
                //UserName = user.UserName;
                //Status = user.Status;
                list.Add(ht);
            }
            Tools.CacheUtil.Insert("alldept_17173ldap", list, 3600);
            return list;
        }
    }
}